package com.psycho.sys.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psycho.sys.api.entity.Announcement;
import com.psycho.sys.api.entity.Appointment;
import com.psycho.sys.api.entity.ConsultationRecord;
import com.psycho.sys.api.entity.Counselor;
import com.psycho.sys.api.entity.User;
import com.psycho.sys.api.mapper.*;
import com.psycho.sys.api.service.AdminService;
import com.psycho.sys.api.vo.AppointmentVO;
import com.psycho.sys.api.vo.ConsultationRecordVO;
import com.psycho.sys.api.vo.CounselorVO;
import com.psycho.sys.api.vo.StatisticsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员服务实现类
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CounselorMapper counselorMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private ConsultationRecordMapper consultationRecordMapper;

    @Autowired
    private AnnouncementMapper announcementMapper;

    @Override
    public Page<User> pageUsers(Integer current, Integer size, String username, String realName, Integer userType,
            Integer status) {
        Page<User> page = new Page<>(current, size);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(username), User::getUsername, username)
                .like(StringUtils.hasText(realName), User::getRealName, realName)
                .eq(userType != null, User::getUserType, userType)
                .eq(status != null, User::getStatus, status)
                .orderByDesc(User::getCreateTime);
        return userMapper.selectPage(page, wrapper);
    }

    @Override
    public Page<CounselorVO> pageCounselors(Integer current, Integer size, String realName, String specialization,
            Integer status) {
        Page<CounselorVO> page = new Page<>(current, size);
        return counselorMapper.selectCounselorWithUser(page, realName, specialization, status);
    }

    @Override
    @Transactional
    public boolean verifyCounselor(Long counselorId, Integer verifyStatus, String verifyRemark) {
        Counselor counselor = counselorMapper.selectById(counselorId);
        if (counselor == null) {
            return false;
        }
        counselor.setStatus(verifyStatus);
        counselor.setRemark(verifyRemark);
        counselor.setUpdateTime(LocalDateTime.now());
        return counselorMapper.updateById(counselor) > 0;
    }

    @Override
    public Page<AppointmentVO> pageAppointments(Integer current, Integer size, Long userId, Long counselorId,
            Integer status) {
        Page<AppointmentVO> page = new Page<>(current, size);
        return appointmentMapper.selectAppointmentWithDetails(page, userId, counselorId, status);
    }

    @Override
    public Page<ConsultationRecordVO> pageRecords(Integer current, Integer size, Long userId, Long counselorId,
            Integer status) {
        Page<ConsultationRecordVO> page = new Page<>(current, size);
        return consultationRecordMapper.selectRecordWithDetails(page, userId, counselorId, status);
    }

    @Override
    public StatisticsVO getStatistics(String startDate, String endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime start = LocalDate.parse(startDate, formatter).atStartOfDay();
        LocalDateTime end = LocalDate.parse(endDate, formatter).plusDays(1).atStartOfDay();

        StatisticsVO vo = new StatisticsVO();

        // 基础统计
        vo.setTotalUsers(userMapper.selectCount(null).intValue());
        vo.setTotalCounselors(counselorMapper.selectCount(null).intValue());

        // 预约统计
        LambdaQueryWrapper<Appointment> appointmentWrapper = new LambdaQueryWrapper<>();
        appointmentWrapper.between(Appointment::getCreateTime, start, end);
        vo.setTotalAppointments(appointmentMapper.selectCount(appointmentWrapper).intValue());

        // 待处理预约
        appointmentWrapper.clear();
        appointmentWrapper.eq(Appointment::getStatus, 0);
        vo.setPendingAppointments(appointmentMapper.selectCount(appointmentWrapper).intValue());

        // 今日预约
        LocalDateTime today = LocalDate.now().atStartOfDay();
        LocalDateTime tomorrow = today.plusDays(1);
        appointmentWrapper.clear();
        appointmentWrapper.between(Appointment::getAppointmentTime, today, tomorrow);
        vo.setTodayAppointments(appointmentMapper.selectCount(appointmentWrapper).intValue());

        // 本月预约
        LocalDateTime monthStart = LocalDate.now().withDayOfMonth(1).atStartOfDay();
        LocalDateTime monthEnd = monthStart.plusMonths(1);
        appointmentWrapper.clear();
        appointmentWrapper.between(Appointment::getAppointmentTime, monthStart, monthEnd);
        vo.setMonthlyAppointments(appointmentMapper.selectCount(appointmentWrapper).intValue());

        // 咨询师评分统计
        LambdaQueryWrapper<Counselor> counselorWrapper = new LambdaQueryWrapper<>();
        counselorWrapper.isNotNull(Counselor::getRating);
        List<Counselor> counselors = counselorMapper.selectList(counselorWrapper);
        double totalRating = counselors.stream()
                .mapToDouble(Counselor::getRating)
                .sum();
        vo.setAverageCounselorRating(counselors.isEmpty() ? 0 : totalRating / counselors.size());

        // 用户满意度（4分以上的评价占比）
        LambdaQueryWrapper<ConsultationRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.between(ConsultationRecord::getCreateTime, start, end)
                .isNotNull(ConsultationRecord::getUserRating);
        long totalRatings = consultationRecordMapper.selectCount(recordWrapper);

        recordWrapper.ge(ConsultationRecord::getUserRating, 4);
        long satisfiedRatings = consultationRecordMapper.selectCount(recordWrapper);
        vo.setUserSatisfaction(totalRatings == 0 ? 0 : (double) satisfiedRatings / totalRatings);

        // 各类型咨询统计
        Map<String, Object> typeStats = new HashMap<>();
        // TODO: 实现咨询类型统计
        vo.setConsultationTypeStats(typeStats);

        // 各时段预约统计
        Map<String, Object> timeSlotStats = new HashMap<>();
        // TODO: 实现时段统计
        vo.setTimeSlotStats(timeSlotStats);

        // 咨询师工作量统计
        Map<String, Object> workloadStats = new HashMap<>();
        // TODO: 实现工作量统计
        vo.setCounselorWorkloadStats(workloadStats);

        return vo;
    }

    @Override
    @Transactional
    public boolean publishAnnouncement(String title, String content, Integer type) {
        Announcement announcement = new Announcement();
        announcement.setTitle(title);
        announcement.setContent(content);
        announcement.setType(type);
        announcement.setStatus(1);
        announcement.setCreateTime(LocalDateTime.now());
        announcement.setUpdateTime(LocalDateTime.now());
        return announcementMapper.insert(announcement) > 0;
    }
}